package com.wdcloud.netlibrary.request;

import android.text.TextUtils;

import com.wdcloud.netlibrary.dispatcher.DownLoadDispatcher;
import com.wdcloud.netlibrary.dispatcher.IDispatcher;

import java.util.Map;


/**
 */
public class DownLoadRequest extends BaseRequest<DownLoadRequest> {

    private String dir;

    private String fileName;

    /**
     * 下载文件目录
     *
     * @param dir
     * @return
     */
    public DownLoadRequest dir(String dir) {
        this.dir = dir;
        return this;
    }

    /**
     * 下载文件名称
     *
     * @param fileName
     * @return
     */
    public DownLoadRequest fileName(String fileName) {
        this.fileName = fileName;
        return this;
    }


    @Override
    protected void buildRequest() {
        if (url == null) {
            throw new RuntimeException("请求路径不能为空");
        }
        StringBuilder sb = new StringBuilder();
        if (params != null) {
            if (url.contains("?") && !url.endsWith("?") && !url.endsWith("&")) {
                sb.append("&");
            } else if (!url.contains("?")) {
                sb.append("?");
            }
            for (Map.Entry<String, String> entry : params.entrySet()) {
                sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
        }
        if (sb.length() > 0) {
            sb.deleteCharAt(sb.length() - 1);
        }
        builder.url(url + sb.toString());
    }


    @Override
    public IDispatcher buildEvent() {
        if (TextUtils.isEmpty(dir) || TextUtils.isEmpty(fileName)) {
            throw new RuntimeException("文件存储路径或名称不能为空");
        }
        buildHeader();
        buildRequest();
        return new DownLoadDispatcher(dir, fileName, builder.build());
    }
}
